package com.ksframework.common.web;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import com.ksframework.common.constant.SysVar;

/**
 * @description
 * 设置系统绝对路径系统常量 及 提供Spring上下文中getBean(String name)方法
 * @author ssocenter
 * @date 2011-8-27
 */
public class SpringUtilListener implements ServletContextListener {
	static Logger log = Logger.getLogger(SpringUtilListener.class);

	private static ServletContext servletContext = null;

	public void contextInitialized(ServletContextEvent servletContextEvent) {
		servletContext = servletContextEvent.getServletContext();
		SysVar.SERVER_ABSOLUTE_PATH = getServerAbsolutePath();
	}

	/**
	 * @作用:通过bean的id从上下文中拿出指定实例对象
	 * @dateTime: May 29, 2009
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		WebApplicationContext context = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		return context.getBean(beanName);
	}

	/**
	 * getRealPath
	 * @return
	 */
	public static String getServerAbsolutePath() {
		return servletContext.getRealPath(File.separator);
	}

	/**
	 * @作用:返回服务器上下文
	 * @return
	 */
	public static ServletContext getServletContext() {
		return servletContext;
	}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
	}
}